<template>
  <div class="residency-application">
    <h1>桂林电子科技大学科技园众创空间</h1>
    <h2>入驻申请书(团队/企业)</h2>
    <div v-if="form.status !== undefined" class="status-display">
      <el-tag :type="getStatusType(form.status)" size="large" effect="dark">
        {{ getStatusText(form.status) }}
      </el-tag>
    </div>
    <el-form
        :model="form"
        :rules="rules"
        label-width="150px"
        ref="formRef"
        style="max-width: 1200px; width: 100%"
        :disabled="form.status !== undefined && form.status !== 0"
    >
      <!-- 基本信息 -->
      <el-card>
        <div slot="header" class="header">基本信息</div>
        <el-form-item label="团队/公司名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入团队或公司的名称" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="申请日期" prop="applyDate">
              <el-date-picker v-model="form.applyDate" type="date" placeholder="点击选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团队/公司人数" prop="numbers">
              <el-input-number v-model="form.numbers" :min="1" placeholder="请输入团队/公司人数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入项目的名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="公司注册时间" prop="registerDate">
              <el-date-picker v-model="form.registerDate" type="date" placeholder="点击选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司组织机构代码" prop="organizationCode">
              <el-input v-model="form.organizationCode" placeholder="请输入公司组织机构代码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="所属行业" prop="industry">
          <el-radio-group v-model="form.industry">
            <el-radio label="电子信息产业" value="电子信息产业">电子信息产业</el-radio>
            <el-radio label="生物医学产业" value="生物医学产业">生物医学产业</el-radio>
            <el-radio label="新能源产业" value="新能源产业">新能源产业</el-radio>
            <el-radio label="新材料产业" value="新材料产业">新材料产业</el-radio>
            <el-radio label="先进制造产业" value="先进制造产业">先进制造产业</el-radio>
            <el-radio label="环保节能减排" value="环保节能减排">环保节能减排</el-radio>
            <el-radio label="高技术服务业" value="高技术服务业">高技术服务业</el-radio>
            <el-radio label="软件外包服务业" value="软件外包服务业">软件外包服务业</el-radio>
            <el-radio label="其他" :value="form.otherIndustry">
              其他
              <el-input
                  v-model="form.otherIndustry"
                  placeholder="请填写其他行业"
                  style="margin-left: 10px; width: 200px"
              />
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否为校友企业" prop="isAlumniEnterprise">
          <el-radio-group v-model="form.isAlumniEnterprise">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否有实际入驻场地" prop="hasPhysicalSpace">
          <el-radio-group v-model="form.hasPhysicalSpace" @change="handleSpaceChange">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.hasPhysicalSpace" label="卡座号" prop="seatNumber">
          <el-input v-model="form.seatNumber" placeholder="请输入卡座号" />
        </el-form-item>
      </el-card>

      <!-- 缴费信息 -->
      <el-card>
        <div slot="header" class="header">缴费信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="缴费类型" prop="paymentType">
              <el-select v-model="form.paymentType" placeholder="请选择缴费类型" multiple>
                <el-option label="保证金" value="deposit"></el-option>
                <el-option label="卡座使用费" value="seatFee"></el-option>
                <el-option label="管理费" value="managementFee"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费金额" prop="paymentAmount">
              <el-input-number v-model="form.paymentAmount" :min="0" placeholder="请输入缴费金额" />
              <span>元</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 联系人信息 -->
      <el-card>
        <div slot="header" class="header">联系人信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人的姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系人的电话号码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 公司信息 -->
      <el-card>
        <div slot="header" class="header">公司信息</div>
        <el-form-item label="公司注册资金" prop="registerMoney">
          <el-input-number
              v-model="form.registerMoney"
              :min="0"
              :max="1000000000"
              placeholder="请输入公司注册资金"
          />
          <span>元</span>
        </el-form-item>
        <el-form-item label="项目/公司股权构成(%)" prop="shareholdingRatio">
          <el-input
              v-model="form.shareholdingRatio"
              type="textarea"
              placeholder="请详细描述项目或公司的股权分配情况"
          />
        </el-form-item>
        <el-form-item label="经营范围（产品/服务）" prop="businessScope">
          <el-input
              v-model="form.businessScope"
              type="textarea"
              placeholder="请简要说明公司的主要产品或服务"
          />
        </el-form-item>
      </el-card>

      <!-- 主要成员信息 -->
      <el-card>
        <div slot="header" class="header">主要成员信息</div>
        <el-form-item label-width="0" prop="members">
          <el-button type="primary" @click="addMember">增加成员</el-button>
          <el-table :data="form.members" style="width: 100%">
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column prop="name" label="姓名">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.name'"
                  :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
                  <el-input v-model="scope.row.name" placeholder="请输入成员姓名" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="department" label="毕业院校">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.department'"
                  :rules="[{ required: true, message: '请输入毕业院校', trigger: 'blur' }]">
                  <el-input v-model="scope.row.department" placeholder="请输入毕业院校" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="major" label="公司研究领域">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.major'"
                  :rules="[{ required: true, message: '请输入公司研究领域', trigger: 'blur' }]">
                  <el-input v-model="scope.row.major" placeholder="请输入公司研究领域" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号码">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.phone'"
                  :rules="[{ required: true, message: '请输入手机号码', trigger: 'blur' },{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }]">
                  <el-input v-model="scope.row.phone" placeholder="请输入手机号码" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="qq" label="QQ号">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.qq'"
                  :rules="[{ required: true, message: '请输入QQ号码', trigger: 'blur' },{ pattern: /^[1-9][0-9]{4,11}$/, message: '请输入正确的QQ号码', trigger: 'blur' }]">
                  <el-input v-model="scope.row.qq" placeholder="请输入QQ号码" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="job" label="公司/团队职务">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.job'"
                  :rules="[{ required: true, message: '请输入在公司或团队中的职务', trigger: 'blur' }]">
                  <el-input v-model="scope.row.job" placeholder="请输入在公司或团队中的职务" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="removeMember(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-card>

      <!-- 项目信息 -->
      <el-card>
        <div slot="header" class="header">项目信息</div>
        <el-form-item label="项目/公司简介（300字以内）" prop="projectIntroduction">
          <el-input
              v-model="form.projectIntroduction"
              type="textarea"
              placeholder="请用300字以内的文字介绍您的项目或公司"
          />
        </el-form-item>
        <el-form-item
            label="您想获得的帮助（如创业辅导、投融资服务、市场推广）"
            prop="helpDescription"
        >
          <el-input
              v-model="form.helpDescription"
              type="textarea"
              placeholder="请告诉我们您希望得到哪些帮助"
          />
        </el-form-item>
      </el-card>

      <!-- 文件上传 -->
      <el-card>
        <div slot="header" class="header">文件上传</div>
        <el-form-item label="身份证明材料" prop="certificate">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'certificate')"
              :limit="1"
              :file-list="certificateList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传团队成员身份证复印件，支持jpg/png/pdf格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.isAlumniEnterprise" label="校友企业证明材料" prop="alumniCertificate">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="handleAlumniCertificateChange"
              :limit="1"
              :file-list="alumniCertificateList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传学校毕业证书等证明材料，支持jpg/png/pdf格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目相关文件" prop="projectfile">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'projectfile')"
              :limit="5"
              :file-list="projectFileList"
              multiple
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传项目相关文件（如奖项、专利、图片等），支持jpg/png/pdf格式，最多5个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="缴费回单" prop="paymentReceipt">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'paymentReceipt')"
              :limit="1"
              :file-list="paymentReceiptList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传缴费回单，支持jpg/png/pdf格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-card>

      <!-- 承诺 -->
      <el-card>
        <div slot="header" class="header">承诺</div>
        <el-form-item class="promise-text">
          <p>
            本团队(公司)承诺上述内容属实，如有任何虚假与隐瞒,本团队(公司)愿承担一切法律责任和后果。
          </p>

          <div style="display: flex; align-items: center; margin: 10px 0;">
            <span style="width: 90px; margin-right: 10px;">承诺人:</span>
            <el-input v-model="form.contactName" placeholder="请在此签名"></el-input>
          </div>
          <p style="margin-left: 20px;">
            日期:
            <el-date-picker v-model="form.applyDate" type="date" placeholder="请选择签署日期" />
          </p>
        </el-form-item>
      </el-card>

      <!-- 审批意见 -->
      <el-card>
        <div slot="header" class="header">审批意见</div>
        <el-form-item label="办公室主任意见">
          <el-input disabled type="textarea" placeholder="等待办公室主任填写意见" />
        </el-form-item>
        <el-form-item label="领导审批意见">
          <el-input disabled type="textarea" placeholder="等待领导填写审批意见" />
        </el-form-item>
      </el-card>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button v-if="form.status === 0" type="primary" @click="submitForm">提交</el-button>
        <el-button v-if="form.status === 0" @click="saveDraft">保存草稿</el-button>
        <el-button v-if="form.status === 0" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <span
    >注：请同时提供团队成员身份证、学生证/教师证复印件及项目相关文件（如奖项、专利、图片等）。</span
    >
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import {
  residencyApplicationList,
  zcresidencyApplication,
  getApplicationFromId,
  editApplication
} from '@/api/enterpeise';
import { getLoginUserId } from '@/utils/storage';
import { uploadFile } from '@/api/file';
import { reqFeedback } from '@/utils/reqFeedback';
// import type { ResidencyApplicationTeam } from '@/types/type';
import type { FormInstance, FormRules, UploadFile } from 'element-plus';
import type { AjaxResult } from '@/types/resultTypes';

// 定义props
interface Props {
  id?: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: ''
});

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();

// 获取模式（查看/编辑）
const mode = ref(route.query.mode as string || 'edit');

// 类型补充
interface ResidencyApplicationTeamExt {
  status?: number;
  id?: number;
  type: number;
  name: string;
  applyDate: string;
  itemName: string;
  numbers: number;
  registerDate: string;
  organizationCode: string;
  industry: string;
  otherIndustry: string;
  isAlumniEnterprise: boolean;
  hasPhysicalSpace: boolean;
  seatNumber: string;
  paymentType: string[];
  paymentAmount: number;
  contactName: string;
  contactPhone: string;
  registerMoney: number;
  shareholdingRatio: string;
  businessScope: string;
  members: Array<{
    name: string;
    department: string;
    major: string;
    phone: string;
    qq: string;
    job: string;
  }>;
  projectIntroduction: string;
  helpDescription: string;
  teacherOpinion: string;
  collegeOpinion: string;
  officeOpinion: string;
  leaderOpinion: string;
  certificate: any;
  alumniCertificate: any;
  paymentReceipt: any;
  projectfile: any[];
}

// 表单数据
const totalRecord = ref(0);
const form = reactive<ResidencyApplicationTeamExt>({
  name: '',
  applyDate: '',
  itemName: '',
  numbers: 0,
  registerDate: '',
  organizationCode: '',
  industry: '',
  otherIndustry: '',
  isAlumniEnterprise: false,
  hasPhysicalSpace: false,
  seatNumber: '',
  paymentType: [],
  paymentAmount: 0,
  contactName: '',
  contactPhone: '',
  registerMoney: 0.0,
  shareholdingRatio: '',
  businessScope: '',
  members: [{
    name: '',
    department: '',
    major: '',
    phone: '',
    qq: '',
    job: '',
  }],
  projectIntroduction: '',
  helpDescription: '',
  teacherOpinion: '',
  collegeOpinion: '',
  officeOpinion: '',
  leaderOpinion: '',
  certificate: null,
  alumniCertificate: null,
  paymentReceipt: null,
  projectfile: [],
  status: 0,
  id: undefined,
  type: 2, // 团队页面类型
});

// 加载现有数据
const loadExistingData = async (id: string) => {
  try {
    const bigIntId = BigInt(id);
    const res = await getApplicationFromId(bigIntId) as any;
    if (res.code === 200) {
      // 处理paymentType字段，将逗号分隔的字符串转换为数组
      if (res.data.paymentType) {
        res.data.paymentType = res.data.paymentType.split(',').map((item: string) => item.trim());
      } else {
        res.data.paymentType = [];
      }
      
      // 字段映射处理
      res.data.shareholdingRatio = res.data.shareholdingRatio || res.data.ShareholdingRatio || '';
      
      Object.assign(form, res.data);
      totalRecord.value = 1; // 编辑模式
    }
  } catch (error) {
    ElMessage.error('加载数据失败');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  const id = props.id || route.query.id;
  if (id) {
    loadExistingData(id.toString());
    totalRecord.value = 1;
  } else {
    totalRecord.value = 0;
    // 其它字段清空，type/status不清空
    // Object.keys(form).forEach(key => {
    //   if (key !== 'status' && key !== 'type') form[key] = Array.isArray(form[key]) ? [] : '';
    // });
    Object.assign(form, {
      name: '',
      applyDate: '',
      itemName: '',
      numbers: 0,
      registerDate: '',
      organizationCode: '',
      industry: '',
      otherIndustry: '',
      isAlumniEnterprise: false,
      hasPhysicalSpace: false,
      seatNumber: '',
      paymentType: [],
      paymentAmount: 0,
      contactName: '',
      contactPhone: '',
      registerMoney: 0.0,
      shareholdingRatio: '', // 修复字段名称
      businessScope: '',
      members: [{
        name: '',
        department: '',
        major: '',
        phone: '',
        qq: '',
        job: '',
      }],
      projectIntroduction: '',
      helpDescription: '',
      teacherOpinion: '',
      collegeOpinion: '',
      officeOpinion: '',
      leaderOpinion: '',
      certificate: null,
      alumniCertificate: null,
      paymentReceipt: null,
      projectfile: [],
      status: 0,
      id: undefined,
      type: 2, // 团队页面类型
    });
  }

  // 初始化至少一个成员
  if (form.members.length === 0) {
    form.members.push({
      name: '',
      department: '',
      major: '',
      phone: '',
      qq: '',
      job: '',
    });
  }
});

// 监听表单数据变化并保存到 localStorage
watch(
  form,
  (newForm) => {
    localStorage.setItem('ResidencyApplicationTeamForm', JSON.stringify(newForm));
  },
  { deep: true }
);

// 增加成员
const addMember = () => {
  formRef.value?.clearValidate('members')
  form.members.push({
    name: '',
    department: '',
    major: '',
    phone: '',
    qq: '',
    job: '',
  });
};

// 删除成员
const removeMember = (index: number) => {
  form.members.splice(index, 1);
};

// 处理是否有实际入驻场地变化
const handleSpaceChange = (val: boolean) => {
  if (!val) {
    form.seatNumber = '';
  }
};

// 表单验证规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入团队/公司名称', trigger: 'blur' }],
  applyDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
  itemName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  numbers: [{ required: true, message: '请输入团队/公司人数', trigger: 'blur' }],
  registerDate: [{ required: true, message: '请选择公司注册时间', trigger: 'change' }],
  organizationCode: [{ required: true, message: '请输入公司组织机构代码', trigger: 'blur' }],
  industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
  isAlumniEnterprise: [{ required: true, message: '请选择是否为校友企业', trigger: 'change' }],
  hasPhysicalSpace: [{ required: true, message: '请选择是否有实际入驻场地', trigger: 'change' }],
  seatNumber: [{ required: true, message: '请输入卡座号', trigger: 'blur' }],
  paymentType: [{ required: true, message: '请选择缴费类型', trigger: 'change' }],
  paymentAmount: [{ required: true, message: '请输入缴费金额', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  registerMoney: [{ required: true, message: '请输入公司注册资金', trigger: 'blur' }],
  shareholdingRatio: [ // 修复字段名称
    { required: true, message: '请输入项目/公司股权构成', trigger: 'blur' },
    { pattern: /^[\d%.,，]*\d+(\.\d+)?[\d%.,，]*$/, message: '只能包含数字、百分号、小数点和逗号，如：张三40%，李四60%', trigger: 'blur' }
  ],
  businessScope: [{ required: true, message: '请输入经营范围', trigger: 'blur' }],
  members: [{
    type: 'array',
    required: true,
    message: '请至少添加一个成员信息',
    trigger: 'change'
  }],
  projectIntroduction: [{ required: true, message: '请输入项目介绍', trigger: 'blur' }],
  helpDescription: [{ required: true, message: '请输入需要帮助描述', trigger: 'blur' }]
});

// 添加文件列表的响应式变量
const certificateList = ref<UploadFile[]>([]);
const alumniCertificateList = ref<UploadFile[]>([]);
const paymentReceiptList = ref<UploadFile[]>([]);
const projectFileList = ref<UploadFile[]>([]);

// 通用文件上传方法
const handleFileUpload = async (file: UploadFile, field: 'certificate' | 'paymentReceipt' | 'projectfile') => {
  if (!file.raw) return;
  const isValidFormat = file.raw.type.includes('image/') || file.raw.type === 'application/pdf';
  if (!isValidFormat) {
    ElMessage.error('只能上传jpg/png/pdf格式的文件！');
    if (field === 'certificate') certificateList.value = [];
    if (field === 'projectfile') projectFileList.value = [];
    if (field === 'paymentReceipt') paymentReceiptList.value = [];
    return false;
  }
  const formData = new FormData();
  formData.append('file', file.raw);
  try {
    const res = await uploadFile(formData);
    (form as any)[field] = res.data.url;
    ElMessage.success('上传成功');
    if (field === 'certificate') certificateList.value = [{...file, url: res.data.url}];
    if (field === 'projectfile') projectFileList.value = [{...file, url: res.data.url}];
    if (field === 'paymentReceipt') paymentReceiptList.value = [{...file, url: res.data.url}];
  } catch (error) {
    ElMessage.error('上传失败');
    if (field === 'certificate') certificateList.value = [];
    if (field === 'projectfile') projectFileList.value = [];
    if (field === 'paymentReceipt') paymentReceiptList.value = [];
  }
};

// 处理校友企业证明文件上传
const handleAlumniCertificateChange = async (file: UploadFile) => {
  const isValidFormat = file.raw?.type.includes('image/') || file.raw?.type === 'application/pdf';
  if (!isValidFormat) {
    ElMessage.error('只能上传jpg/png/pdf格式的文件！');
    alumniCertificateList.value = [];
    return false;
  }
  form.alumniCertificate = file;
};

// 格式化日期为YYYY-MM-DD
function formatDateToYMD(dateStr: string): string {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 修改提交表单函数
const submitForm = async () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      // 日期格式化
      if (form.applyDate) form.applyDate = formatDateToYMD(form.applyDate);
      if (form.registerDate) form.registerDate = formatDateToYMD(form.registerDate);
      // 兼容 projectfile 字段类型，后端只接受字符串
      if (Array.isArray(form.projectfile)) {
        form.projectfile = form.projectfile.length > 0 ? form.projectfile[0] : '';
      }
      // 兼容 paymentType 字段类型，后端只接受字符串
      if (Array.isArray(form.paymentType)) {
        form.paymentType = form.paymentType.join(',');
      }
      // 处理shareholdingRatio字段映射
      const submitData = {
        ...form,
        ShareholdingRatio: form.shareholdingRatio
      };
      
      try {
        const api = totalRecord.value === 1 ? editApplication : zcresidencyApplication;
        const res = await api(submitData as any);
        if (res.code === 200) {
          ElMessage.success(totalRecord.value === 1 ? '更新成功' : '提交成功');
          localStorage.removeItem('ResidencyApplicationTeamForm');
          router.push('/personal-center/enterprise-settlement/my-application');
        }
      } catch (error) {
        ElMessage.error('提交失败');
      }
    } else {
      ElMessage.error('表单信息有误或未填写完整');
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  form.name = '';
  form.applyDate = '';
  form.itemName = '';
  form.numbers = 0;
  form.registerDate = '';
  form.organizationCode = '';
  form.industry = '';
  form.otherIndustry = '';
  form.isAlumniEnterprise = false;
  form.hasPhysicalSpace = false;
  form.seatNumber = '';
  form.paymentType = [];
  form.paymentAmount = 0;
  form.contactName = '';
  form.contactPhone = '';
  form.registerMoney = 0.0;
  form.shareholdingRatio = '';
  form.businessScope = '';
  form.members = [{
    name: '',
    department: '',
    major: '',
    phone: '',
    qq: '',
    job: '',
  }];
  form.projectIntroduction = '';
  form.helpDescription = '';
  form.teacherOpinion = '';
  form.collegeOpinion = '';
  form.officeOpinion = '';
  form.leaderOpinion = '';
  certificateList.value = [];
  alumniCertificateList.value = [];
  paymentReceiptList.value = [];
  projectFileList.value = [];
  localStorage.removeItem('ResidencyApplicationTeamForm'); // 重置表单时清除本地存储
};

const isSubmit = ref(false);

const saveDraft = async () => {
  try {
    // 日期格式化
    if (form.applyDate) form.applyDate = formatDateToYMD(form.applyDate);
    if (form.registerDate) form.registerDate = formatDateToYMD(form.registerDate);
    // 兼容 projectfile 字段类型，后端只接受字符串
    if (Array.isArray(form.projectfile)) {
      form.projectfile = form.projectfile.length > 0 ? form.projectfile[0] : '';
    }
    // 兼容 paymentType 字段类型，后端只接受字符串
    if (Array.isArray(form.paymentType)) {
      form.paymentType = form.paymentType.join(',');
    }
    // 处理shareholdingRatio字段映射
    const submitData = {
      ...form,
      ShareholdingRatio: form.shareholdingRatio
    };
    
    console.log( "表单数据",submitData);
    const api = totalRecord.value === 1 ? editApplication : zcresidencyApplication;
    const res = await api(submitData as any);
    if (res.code === 200) {
      ElMessage.success('草稿保存成功');
      localStorage.removeItem('ResidencyApplicationTeamForm');
      router.push('/personal-center/enterprise-settlement/my-application');
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

// 状态标签工具函数
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'info';
    case 1: return 'warning';
    case 2: return 'success';
    case 3: return 'danger';
    default: return 'info';
  }
};
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '草稿';
    case 1: return '已提交';
    case 2: return '审核通过';
    case 3: return '审核失败';
    default: return '未知状态';
  }
};

</script>

<style lang="scss" scoped>
.header {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}
.el-card {
  margin: 20px auto;
}
.residency-application {
  width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: bold;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-table th, .el-table td) {
    font-weight: bold;
  }
}
.promise-text {
  :deep(.el-form-item__content) {
    font-size: large;
  }
}
.status-display {
  margin-bottom: 20px;
  text-align: center;
  .el-tag {
    font-size: 16px;
    padding: 8px 16px;
  }
}
</style>
